//
// Created by 王乐 on 2022/2/5.
//

#include "LeQuadRenderer.h"
#include "glad/glad.h"

#include "LeVBOManager.h"
#include "LeUtils.h"

#include "LeCameraManager.h"

#include "LeTransform.h"

#include "glm/gtc/matrix_transform.hpp"

LeQuadRenderer::LeQuadRenderer()
{

}

LeQuadRenderer::~LeQuadRenderer()
{

}

void LeQuadRenderer::preLoopRender()
{
    unsigned int VBO;
    LeVBOManager::findVBO("Quad", VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);
}

void LeQuadRenderer::render()
{
    if(!m_GameObject->isActive())
        return;

    glm::mat4 projection =  LeCameraManager::getProjectionMatrix();
    glm::mat4 view = LeCameraManager::getViewMatrix();

    // be sure to activate shader when setting uniforms/drawing objects
    m_Shader.useShader();

    m_Shader.setMat4("projection", projection);
    m_Shader.setMat4("view", view);

    glm::mat4 model = m_GameObject->m_Transform.getModelMatrix();
    model = glm::scale(model, glm::vec3(1.03f, 1.03f, 1.0f));
    m_Shader.setMat4("model", model);

    m_Shader.setInt("material.diffuse", 0);
    // bind diffuse map
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, diffuseMap);

    // render the cube
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 6);
}

void LeQuadRenderer::postLoopRender()
{
    glDeleteVertexArrays(1, &VAO);
}

void LeQuadRenderer::addSprite(const char *diffuseMapPath)
{
    diffuseMap = LeTextureLoader().loadTexture(diffuseMapPath);
}
